package com.ogawa.chair7808.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.ogawa.base.Constant.Constants;
import com.ogawa.base.download.AlertDialogUpdata;
import com.ogawa.base.download.AlertDialogUpdataProgress;
import com.ogawa.base.download.DownloadApkRequest;
import com.ogawa.base.download.DownloadInfoBean;
import com.ogawa.base.download.DownloadThreadPool;
import com.ogawa.base.network.bean.BeanUpdata;
import com.ogawa.base.utils.CommonUtil;
import com.ogawa.base.utils.DownTimer;
import com.ogawa.base.utils.statusbar.SystemStatusBarUtil;
import com.ogawa.base.utils.util.Utils;
import com.ogawa.chair7808.R;
import com.ogawa.chair7808.interfaces.OnAutoFinish;
import com.ogawa.chair7808.interfaces.OnTimeChoose;
import com.ogawa.chair7808.manager.DataManager;
import com.ogawa.chair7808.observer.ShowLoadingObserver;
import com.ogawa.chair7808.view.loopview.LoopView;
import com.ogawa.chair7808.view.loopview.OnItemSelectedListener;
import com.ogawa.chair7808.widget.LayoutNormalTitle7506;
import com.example.reslib.utils.DisplayUtil;
import com.example.reslib.utils.ToastUtils;
import com.example.reslib.view.kprogresshud.KProgressHUD;
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity;
import com.umeng.analytics.MobclickAgent;

import java.lang.ref.WeakReference;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;


/**
 * Activity 的基类封装
 * Created by HourGlassRemember on 2018/8/6.
 */
public  abstract class BaseActivity extends RxAppCompatActivity implements ShowLoadingObserver.onLoadingShow {
    protected static final String TAG = "BaseActivity";
    private OnTimeChoose listener;
    private String mName;
    private FrameLayout frameLayout;
    public KProgressHUD kProgressHUD;
    public LayoutNormalTitle7506 titleBar;
    private String mTime= Constants.TIME_15;
    private    AlertDialog alertDialogFinish;
    private Dialog loadingDialog;

    private AlertDialogUpdata mAler;
    private AlertDialogUpdataProgress mAlertProgress;
    private DownloadApkRequest request;
    protected MyHandler mHandler;
    private boolean isDownFaile;
    private BeanUpdata mUpdataBean;
    private NumberFormat numberFormat;
    private long mCountTime;
    private DownTimer mTimer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chair_7808_activity_base);// 设置布局
        mHandler =  new MyHandler(this);
        kProgressHUD = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE);
        numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(2);
        initView(setLayoutId());// 初始化视图
        initSystemBar();
        loadData();
        initTitleBar();// 初始化标题栏
        setDark(true);
        ShowLoadingObserver.getInst().registerObserver(this);

    }
    public void loadData(){}

    public String getmName() {
        return mName;
    }

    public void setmName(String mName) {
        this.mName = mName;
    }

    public void initSystemBar() {
        SystemStatusBarUtil.setStatusBar(this);// 沉浸式状态

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            setTranslucentStatus(activity, true);
//        }
//        SystemBarTintManager tintManager = new SystemBarTintManager(activity);
//        tintManager.setStatusBarTintEnabled(true);
//        tintManager.setStatusBarTintResource(R.color.transparent);// 使用颜色资源
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    /**
     * 初始化标题栏
     *
     * @return
     */
    public void initTitleBar() {
        titleBar = findViewById(R.id.title_bar);
    }
    /**
     * 显示或隐藏标题栏
     *
     * @param flag
     */
    public void showTitleBar(boolean flag) {
        titleBar.setVisibility(flag ? View.VISIBLE : View.GONE);
    }
    @TargetApi(19)
    private static void setTranslucentStatus(Activity activity, boolean on) {
        Window win = activity.getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }



    /**
     * 初始化视图
     *
     * @param layoutId 布局 ID
     */
    public void initView(int layoutId) {
        frameLayout = findViewById(R.id.frame_layout_content);
        frameLayout.addView(LayoutInflater.from(this).inflate(layoutId, null), 0);
    }
    public void setBackGround(int resId){
        findViewById(R.id.root_view).setBackgroundResource(resId);
    }



    public void showkProgress(String notice) {
        kProgressHUD.setLabel(notice);
        kProgressHUD.show();
    }


    public void canclekProgress() {
        if (kProgressHUD != null && kProgressHUD.isShowing()) {
            kProgressHUD.dismiss();
        }

    }

    /**
     * @param isDark 状态栏字体颜色是否深色
     */
    public void setDark(boolean isDark) {
        Utils.setStatusBar(this, false, false);
        Utils.setStatusTextColor(isDark, this);
    }

    /**
     * 设置标题栏以下布局 ID
     *
     * @return
     */
    public abstract int setLayoutId();

    @SuppressLint("CheckResult")
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart()");
        Observable.interval(1, TimeUnit.SECONDS)
                .doOnDispose(new Action() {
                    @Override
                    public void run() throws Exception {
//                        Log.i(TAG, "doOnDispose --- 从onStart()中调用取消订阅");
                    }
                })
                .compose(this.<Long>bindToLifecycle())// bindToLifecycle的自动取消订阅，因为是在onStart的时候调用，所以在onStop的时候自动取消订阅
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
//                        Log.i(TAG, "doOnDispose --- 在onStart的时候调用，在onStop的时候自动取消订阅");
                    }
                });
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop()");
    }

    public void showDialog() {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        LayoutInflater inflater =this.getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_loopview_7808, null);
        dialogBuilder.setView(dialogView);
        TextView mTvCancle = dialogView.findViewById(R.id.dialog_cancle);
        TextView mTvOk = dialogView.findViewById(R.id.dialog_ok);

        LoopView loopView = (LoopView) dialogView.findViewById(R.id.loopView_7506);
        final ArrayList<String> list = new ArrayList<>();
        list.add(Constants.TIME_5);
        list.add(Constants.TIME_10);
        list.add(Constants.TIME_15);
        list.add(Constants.TIME_20);
        list.add(Constants.TIME_25);
        list.add(Constants.TIME_30);
        //  滚动监听
        loopView.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                mTime = list.get(index);
//                if(listener != null){
//                    listener.onTimeListener(mTime);
//                }
            }
        });

        // 设置原始数据
        loopView.setItems(list);
        loopView.setCurrentPosition(2);
        loopView.setItemsVisibleCount(5);
        loopView.setDividerColor(getResources().getColor(R.color.white));
        loopView.setOuterTextColor(Color.GRAY);
        loopView.setCenterTextColor(Color.CYAN);
        final AlertDialog alertDialog = dialogBuilder.create();
        //加上下面两句才能显示圆角 不然圆角处会有白色效果
        Window window = alertDialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        alertDialog.setCancelable(false);
        alertDialog.show();
        mTvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
            }
        });
        mTvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener != null&&!TextUtils.isEmpty(mTime)){
                    listener.onTimeListener(mTime);
                    alertDialog.cancel();
                }
            }
        });
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = (int)(DisplayUtil.getScreenWidthPx(this)*0.9); //设置宽度
        window.setAttributes(lp);


    }


    /**
     *
     * @param type  1:专业按摩详情
     */
    public void showFinishDialog(Activity activity,final String type, View.OnClickListener listener) {
        if(alertDialogFinish == null){
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
            LayoutInflater inflater =this.getLayoutInflater();
            View dialogView = inflater.inflate(R.layout.dialog_finish, null);
            dialogBuilder.setView(dialogView);
            TextView mTvOk = dialogView.findViewById(R.id.dialog_finish_ok);
            TextView mTvEnd = dialogView.findViewById(R.id.end_tv2);
            if(type.equals("1")){
                mTvEnd.setVisibility(View.VISIBLE);
            }
            else {
                mTvEnd.setVisibility(View.GONE);
            }
            alertDialogFinish = dialogBuilder.create();
            //加上下面两句才能显示圆角 不然圆角处会有白色效果
            Window window = alertDialogFinish.getWindow();
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            alertDialogFinish.setCancelable(false);
            if(activity!=null&&!activity.isFinishing()){
                alertDialogFinish.show();
            }

            mTvOk.setOnClickListener(listener);

            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = (int)(DisplayUtil.getScreenWidthPx(this)*0.9); //设置宽度
            window.setAttributes(lp);
        }else {
            if(activity!=null&&!activity.isFinishing()){
                alertDialogFinish.show();
            }

        }



    }
    public boolean isFinishDialogShowing(){
        if(alertDialogFinish!=null){
            return alertDialogFinish.isShowing();

        }else {
            return false;
        }
    }
    public void cancleFinishDialog(){
        if(alertDialogFinish!=null){
            alertDialogFinish.cancel();
        }
    }



    public void showNoticeDialog(final OnAutoFinish autolistener) {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        LayoutInflater inflater =this.getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_to_advance, null);
        dialogBuilder.setView(dialogView);
        TextView mTvCancle = dialogView.findViewById(R.id.dialog_cancle);
        TextView mTvOk = dialogView.findViewById(R.id.dialog_ok);


        final AlertDialog alertDialog = dialogBuilder.create();
        //加上下面两句才能显示圆角 不然圆角处会有白色效果
        Window window = alertDialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        alertDialog.setCancelable(false);
        alertDialog.show();
        mTvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                alertDialog.cancel();
            }
        });
        mTvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                autolistener.onAutoClose();
                alertDialog.cancel();
            }
        });
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = (int)(DisplayUtil.getScreenWidthPx(this)*0.9); //设置宽度
        window.setAttributes(lp);


    }



    public void setTimeListener( OnTimeChoose listener){
        this.listener = listener;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        titleBar.onDestory();
        alertDialogFinish = null;
        ShowLoadingObserver.getInst().removeObserver(this);
    }





    public void getPer(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){//未开启定位权限
            //开启定位权限,200是标识码
            Log.e("getPer","nopomission");
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},200);
        }else{
            Log.e("getPer","haspomission");
            onPermissionSuccess();
        }

    }
    public void getPerWrite(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){//
            //开启定位权限,200是标识码
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},201);
        }else{
            showUpdataAlert(mUpdataBean);
        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 200://刚才的识别码
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//用户同意权限,执行我们的操作
                    onPermissionSuccess();//开始定位
                } else {//用户拒绝之后,当然我们也可以弹出一个窗口,直接跳转到系统设置页面
//                    showPermissionDialog() ;
                    ToastUtils.showShortToast(this,"缺少定位权限无法进行网络配置，请打开相应权限");
                }
                break;
            case 201://刚才的识别码
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//用户同意权限,执行我们的操作
                    showUpdataAlert(mUpdataBean);
                } else {//用户拒绝之后,当然我们也可以弹出一个窗口,直接跳转到系统设置页面
//                    showPermissionDialog() ;
                    showPermissionDialog() ;
                }
                break;
            default:
                break;
        }

    }


    //权限等
    public void onPermissionSuccess() {

    }

    /**
     * 升级提示
     * @param bean
     */
    private void showUpdataAlert(final BeanUpdata bean){
        mAler = new AlertDialogUpdata(this,bean,new AlertDialogUpdata.OnDialogListener(){

            @Override
            public void onClick() {
                if(bean.getIsforce()==1){
                    ToastUtils.showShortToast(BaseActivity.this,"请升级后使用");
                    BaseActivity.this.finish();
                }
                else {
                    mAler.dismiss();
                }
            }
        }, new AlertDialogUpdata.OnDialogListener() {
            @Override
            public void onClick() {
                Log.e("showUpdata","showUpdataAlert");

                mAlertProgress = new AlertDialogUpdataProgress(BaseActivity.this,bean.getNotice());
                fileDownload(bean.getUrl());
                mAlertProgress.setCancelable(false);
                mAlertProgress.show();
                mAler.dismiss();
                mAlertProgress.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        //处理监听事件
                        Log.e("showUpdata","onDismiss");
                        DownloadThreadPool.getInstance().removeTask(request);
//                        if (request.getIsRunning()) {
//                            request.exit();
//                        }

                    }
                });

            }
        });
        mAler.setCancelable(false);
        mAler.show();


    }


    /**
     * 权限设置
     */
    private AlertDialog mPermissionDialog;
    private void showPermissionDialog() {
        if (mPermissionDialog == null) {
            mPermissionDialog = new AlertDialog.Builder(this)
                    .setMessage("已禁用权限，请手动授予")
                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mPermissionDialog.cancel();
                            Uri packageURI = Uri.parse("package:" + getPackageName());
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                            startActivityForResult(intent, 2);

                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mPermissionDialog.cancel();
                        }
                    })
                    .create();
        }
        mPermissionDialog.show();
        mPermissionDialog.setCanceledOnTouchOutside(false);
        Button button = mPermissionDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        button.setTextColor(this.getResources().getColor(R.color.red));
        button.setTextSize(TypedValue.COMPLEX_UNIT_SP,13);
        Button button2 = mPermissionDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        button2.setTextColor(this.getResources().getColor(R.color.color_2121));
        button2.setTextSize(TypedValue.COMPLEX_UNIT_SP,13);
    }

    /**
     * 等待
     */
    public void showloading() {
        if(loadingDialog==null){
            loadingDialog = new Dialog(this, R.style.DialogTheme);
            loadingDialog.setContentView(R.layout.layout_softap_progressbar);
            loadingDialog.setCancelable(true);
            loadingDialog.show();
        }
        else {
            loadingDialog.show();

        }

    }
    public void cancleloading() {
        if(loadingDialog!=null){
            loadingDialog.cancel();
        }

    }


    @Override
    public void onShowLoading() {
        showloading();
    }

    @Override
    public void onCancleLoading() {
        cancleloading();
    }

    /**
     * 更新
     */
    public void doUpdata(BeanUpdata bean){
        if(bean!=null&&!TextUtils.isEmpty(bean.getUrl())){
            mUpdataBean = bean;
            getPerWrite();

        }


    }


    public void fileDownload(String url) {
        request = new DownloadApkRequest(this, mHandler, url, new DownloadApkRequest.IDownloadApkInterProgress() {
            @Override
            public void onDownloadWait(DownloadInfoBean apkInfoBean) {
                isDownFaile = false;
            }

            @Override
            public void onDownloadStart(DownloadInfoBean apkInfoBean) {
                isDownFaile = false;
            }

            @Override
            public void onDownloadProgress(DownloadInfoBean apkInfoBean) {
                isDownFaile = false;
                String downloadLength = Formatter.formatFileSize(getApplicationContext(), apkInfoBean.getCurrentPos());
                String totalLength = Formatter.formatFileSize(getApplicationContext(), apkInfoBean.getEndPos());
                String size = downloadLength + "/" + totalLength;
                String speed = Formatter.formatFileSize(getApplicationContext(), apkInfoBean.getSpeed());
                String mSpeed = String.format("%s/s", speed);
                float pre = ((float)apkInfoBean.getCurrentPos())/((float)apkInfoBean.getEndPos());
                Log.e("cucucu",pre+"");
                String precent = numberFormat.format(pre);
                int mProgress = (int) (pre* 100);
                mAlertProgress.refreshView(size,precent,mSpeed,mProgress);
            }

            @Override
            public void onDownloadEnd(DownloadInfoBean dib) {
                Log.e("path",dib.getSavePath()+"");
                mAlertProgress.dismiss();

                CommonUtil.installApk(BaseActivity.this,dib.getSavePath());
            }

            @Override
            public void onDownloadFailed(DownloadInfoBean apkInfoBean, String errMsg) {
                isDownFaile =true;
                Log.e(TAG,errMsg+"");
                mAlertProgress.dismiss();
//                Log.e("isDownFaile",errMsg+"");
            }

        });
        DownloadThreadPool.getInstance().addTask(request);

    }

    protected static class MyHandler extends Handler {

        private WeakReference<BaseActivity> wr;

        public MyHandler(BaseActivity activity) {
            wr = new WeakReference<BaseActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if(wr != null && wr.get() != null){
                wr.get().handleMessage(msg);
            }
        }

    }
    public void handleMessage(Message msg) {

    }


    public void pauseTime(){
        if(mTimer!=null){
            mTimer.pause();
        }

    }
    public void reStarTime(){
        if(mTimer!=null){
            mTimer.resume();
        }
    }
    public void cancelTime(){
        if(mTimer!=null){
            mTimer.cancel();
        }
    }

//    public void doUpDataTime(String min,String sec){
//        if(DataManager.getInst().isRunning()) {
//            if(!(min.equals("0")&&sec.equals("0"))){
//                long time = (Integer.valueOf(min)*60+Integer.valueOf(sec));
//                if(Math.abs(time-mCountTime)>30){
//                    setTime(Integer.valueOf(min),Integer.valueOf(sec));
//                }
//            }else {
//                mCountTime=0;
//            }
//
//        }else {
//            cancelTime();
//            mCountTime=0;
//        }
//    }

//    public void timeFinish(){
//    }
//    public void setTime(int min,int sec){
//        cancelTime();
//        if(DataManager.getInst().isRunning()){
//            mTimer = new DownTimer();//实例化
//            mTimer.setTotalTime(min*60*1000+sec*1000);//设置毫秒数
//            mTimer.setIntervalTime(1000);//设置间隔数
//            mTimer.setTimerLiener(new DownTimer.TimeListener() {
//                @Override
//                public void onFinish() {
//                    mCountTime=0;
//                    timeFinish();
//                }
//                @Override
//                public void onInterval(long time) {
//                    long showTime =time/1000;
//                    mCountTime = showTime;
//                    if(!DataManager.getInst().isRunning()){
//                        cancelTime();
//                    }
//                }
//            });
//            mTimer.start();
//        }else {
//            cancelTime();
//            mCountTime=0;
//        }
//    }

}
